const app = require("express")();
const {
	addOne,
	updateOne,
	queryOne,
} = require("../models/login/index");

const { getToken } = require('../token/index');
/**
 * A song type
 * @typedef {object} UerInfo
 * @property {string} account.required - 账号
 * @property {string} password.required - 密码
 */

/**
 * POST /login
 * @tags 登录注册
 * @summary 登录
 * @description 登录
 * @param {UerInfo} request.body.required - 账号信息
 * @return {array<Song>} 200 - success response - application/json
 */
app.post("/login", async (req, res) => {
	try {
		const parmas = req.body;
		const result = await queryOne(parmas);
		if (result) {
			const token = getToken({ id: result._id });
			res.API({
				token,
				userInfo: result
			});
		} else {
			res.status(400).json({ message: '账号或密码不正确！' })
		}

	} catch (err) {
		res.API_ERROR(err.msg, 1002, err?.mapped?.());
	}
});

/**
 * POST /register
 * @tags 登录注册
 * @summary 注册
 * @description 注册
 */
app.post("/register", async (req, res) => {
	try {
		const parmas = req.body;
		const result = await addOne(parmas);
		res.API(result);
	} catch (err) {
		res.API_ERROR(err.msg, 1002, err?.mapped?.());
	}
});

/**
 * POST /resetPassword
 * @tags 登录注册
 * @summary 重置密码
 * @description 重置密码
 */
app.post("/resetPassword", async (req, res) => {
	try {
		const parmas = req.body;
		const id = { _id: parmas };
		const result = await updateOne(id);
		res.API(result);
	} catch (err) {
		res.API_ERROR(err.msg, 1002, err?.mapped?.());
	}
});

module.exports = app;
